//
//  MusicViewController.m
//  享动
//
//  Created by lanou on 16/4/7.
//  Copyright © 2016年 HHUI. All rights reserved.

#import "MusicViewController.h"
#import "musicrunCell.h"
#import "RequestManager.h"
#import "MusicDetailViewController.h"
#import "musicRunModel.h"
#import <UIImageView+WebCache.h>
#import "HYAwesomeTransition.h"
#import "MusicDetailTableViewCell.h"
#import <FMDatabase.h>
#import "musicListModel.h"
#import "MusicChooseViewController.h"
#import "one.h"
#import "two.h"
typedef NS_ENUM(NSInteger,editState)
{
    NormalState,
    
    DeleteState
    
};

@interface MusicViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ModalViewControllerDelegate,UIViewControllerTransitioningDelegate,UITableViewDataSource,UITableViewDelegate>


@property(nonatomic,strong)NSArray * musicUrlArray;

@property(nonatomic,strong)HYAwesomeTransition *  awesometransition;
@property (nonatomic, weak) UICollectionViewCell *transitionCell;

@property (nonatomic, strong) UITableView *twoTableView;

@property (weak, nonatomic) IBOutlet UIView *bigView;

@property (weak, nonatomic) IBOutlet UIButton *musiclistButton;

@property (weak, nonatomic) IBOutlet UIButton *mymusicButton;
@property(nonatomic,strong)NSMutableArray * tempArray;

@property(nonatomic,strong)NSMutableArray * modelArray;

@property(nonatomic,strong)NSMutableArray *titleArray;

@property(nonatomic,strong)UIButton * editButton;

@property(nonatomic,assign)editState editState;

@property(nonatomic,strong)FMDatabase * db;

@property(nonatomic,strong)UILongPressGestureRecognizer * longPressGr;

@property(nonatomic,strong)NSMutableArray * nameArray;

@end

@implementation MusicViewController

+ (MusicViewController *)shareInstence
{
    static MusicViewController * vc = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        vc = [[MusicViewController alloc]init];
    });
    return vc;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:229 / 255.0 blue:234 / 255.0 alpha:1];
    // 动画代码----------------------------------
    self.awesometransition = [[HYAwesomeTransition alloc] init];
    self.awesometransition.duration = 1.5f;
    self.awesometransition.containerBackgroundView = ({
        UIView *bgView = (UIView *)[[[NSBundle mainBundle] loadNibNamed:@"ContainerBackgroundView" owner:nil options:nil] lastObject];
        bgView;
    });

    
    

    self.twoTableView = [[UITableView alloc]initWithFrame:CGRectMake(KWIDTH, 0, KWIDTH, KHEIGHT-120-49)];
    self.twoTableView.backgroundColor = [UIColor clearColor];
    self.twoTableView.dataSource = self;
    self.twoTableView.delegate = self;
    [self.twoTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.bigView addSubview:_twoTableView];
    // 动画代码----------------------------------


    
    
    _musicListArray = [NSMutableArray array];
    
    // 数据库
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"musicList.db"];
    
    NSLog(@"%@",path);
    self.db = [FMDatabase databaseWithPath:path];
    
    if (![self.db open]) {
        NSLog(@"不能打开数据库");
    }
    
    // 创建表
    
    [_db executeUpdate:@"CREATE TABLE musicList (listName text,iconViewData blot ,introduce text)"];
    
    FMResultSet * rs = [_db executeQuery:@"SELECT * FROM musicList"];
    
    while ([rs next]) {
        musicListModel * model = [[musicListModel alloc]init];
        model.listName = [rs stringForColumn:@"listName"];
        model.iconViewData = [rs dataForColumn:@"iconViewData"];
        model.introduce = [rs stringForColumn:@"introduce"];
        [_musicListArray addObject:model];
        
    }
    
    [rs close];
    

    _musicUrlArray = @[@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=93b67e0dfaac41078bc7666729f8e993&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&scene=3&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=f98cebca56614844b86bfccd6a725f17&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&scene=2&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=b9d632d4710a49b6830ea250bddff31d&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&scene=1&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=23afcd25481f4710bb760935bf818599&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&scene=4&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=df6f697add4c44f6aa0d328b7726d93d&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&scene=5&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=a87cc5e228db4a82bdfffedbcd600b86&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&scene=6&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=d37e9a14a5c5432da2fd4f3806b2c9a7&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&scene=7&uid=301026"];
    
    self.scrolllView.delegate = self;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationItem.title = @"享听";
    
    
    [self.musiclistButton addTarget:self action:@selector(musiclist) forControlEvents:UIControlEventTouchUpInside];
    self.musiclistButton.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
    [self.mymusicButton addTarget:self action:@selector(mymusic) forControlEvents:UIControlEventTouchUpInside];
    [self.musiclistButton.layer setCornerRadius:5];
    [self.mymusicButton.layer setCornerRadius:5];
    
    self.scrolllView.delegate = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"享听";
    
    self.conllectionView.delegate = self;
    self.conllectionView.dataSource = self;
    self.conllectionView.backgroundColor = [UIColor whiteColor];
    [self.conllectionView registerClass:[musicrunCell class] forCellWithReuseIdentifier:@"cell"];
    
    self.conllectionView.backgroundColor = [UIColor clearColor];
    
    NSArray * imageArr = @[@"http://f.igeekery.com/1001/d2375d96a619485ea744a51c082a5e4a.jpg",@"http://f.igeekery.com/1001/e12ee3b865a1475da0106b9e06a3babb.jpg",@"http://f.igeekery.com/1001/917e3b493f8541d6b8febe1a837c683c.jpg",@"http://f.igeekery.com/1001/b4f90c2a6d784bbcad5a910a1777cf50.jpg",
        @"http://f.igeekery.com/1001/d499c353cc024f62a82fb9b343e0b973.jpg",@"http://f.igeekery.com/1001/fc5b6021005f415e8d09f379668a4f73.jpg",@"http://f.igeekery.com/1001/6d9db5b51656490c9bc7963dade9ebd2.jpg"];
    
    _modelArray = [NSMutableArray arrayWithArray:imageArr];
    
     NSArray * titile = @[@"慢跑",@"中跑",@"快跑",@"健走",@"热身",@"放松",@"街舞音乐"];
    _titleArray = [NSMutableArray arrayWithArray:titile];
    
    
    [self getView];
    
    
    _editButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _editButton.frame = CGRectMake(KWIDTH - 40, 7, 30, 30);
    [_editButton setTitle:@"编辑" forState:UIControlStateNormal];
    [_editButton addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:_editButton];
    self.editState = NormalState;
    
    
}
// 编辑模式按钮
- (void)edit
{
    if (self.editState == NormalState) {
        
        for (musicrunCell * cell in _conllectionView.visibleCells) {

            if (cell.tag < _modelArray.count + _musicListArray.count) {
                // =====
                CALayer*viewLayer=[cell layer];
                CABasicAnimation*animation=[CABasicAnimation animationWithKeyPath:@"transform"];
                animation.duration=0.2;
                animation.repeatCount = 100000;
                animation.autoreverses=YES;
                animation.fromValue=[NSValue valueWithCATransform3D:CATransform3DRotate
                                     
                                     (viewLayer.transform, -0.03, 0.0, 0.0, 0.03)];
                animation.toValue=[NSValue valueWithCATransform3D:CATransform3DRotate
                                   
                                   (viewLayer.transform, 0.03, 0.0, 0.0, 0.03)];
                [viewLayer addAnimation:animation forKey:@"wiggle"];
            }
            
            if (cell.tag >=7 && cell.tag < _modelArray.count + _musicListArray.count) {
                cell.deleteButton.hidden = NO;
                
               
            }
        }

        [_editButton setTitle:@"完成" forState:UIControlStateNormal];
        self.editState = DeleteState;
    }
    else
    {
        
        for (musicrunCell * cell in _conllectionView.visibleCells) {
            [cell.layer removeAllAnimations];

            if (cell.tag >=7 && cell.tag < _modelArray.count + _musicListArray.count) {
                cell.deleteButton.hidden = YES;
         }
        }

       [_editButton setTitle:@"编辑" forState:UIControlStateNormal];
         self.editState = NormalState;
    }
}


- (void)viewWillDisappear:(BOOL)animated
{
    
    [_nameT resignFirstResponder];
    [_nameT1 resignFirstResponder];
    
    [_editButton setTitle:@"编辑" forState:UIControlStateNormal];
    
    self.editState = NormalState;
    
    for (musicrunCell * cell in _conllectionView.visibleCells) {
   
        cell.deleteButton.hidden = YES;
        [cell.layer removeAllAnimations];
       
    }

    
    // 隐藏编辑button
    _editButton.hidden  = YES;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
 name:UIKeyboardWillHideNotification object:self];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    if (_scrolllView.contentOffset.x / KWIDTH == 0) {
         _editButton.hidden  = NO;
        
        self.editState = NormalState;
        
        [self.editButton setTitle:@"编辑" forState:UIControlStateNormal];
      
        
    }
   
   
    // 添加键盘弹出的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoard:) name:UIKeyboardWillShowNotification object:nil];
        
    // 添加键盘回收的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Back:) name:UIKeyboardWillHideNotification object:nil];
    
    self.automaticallyAdjustsScrollViewInsets = NO;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil]; //监听是否触发home键挂起程序.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil]; //监听是否重新进入程序.
    
}

-(void)applicationWillResignActive {
   
    
    [_editButton setTitle:@"编辑" forState:UIControlStateNormal];
    self.editState = NormalState;
    for (musicrunCell * cell in _conllectionView.visibleCells) {
        
        cell.deleteButton.hidden = YES;
        [cell.layer removeAllAnimations];
        
    }

}

-(void)applicationDidBecomeActive {
   
 
}


- (void)getView
{
    // 添加歌单
    _addView = [[UIView alloc]initWithFrame:CGRectMake((KWIDTH-10)/2, KHEIGHT - 10, 0 , 0)];
    
    _addView.backgroundColor = [UIColor darkGrayColor];
    
    [self.view addSubview:_addView];
    
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 70, 20)];
    label.text = @"歌单名称";
    label.textColor = [UIColor whiteColor];
    [_addView addSubview:label];
    
    _nameT = [[UITextField alloc]initWithFrame:CGRectMake(10, 35, (KWIDTH - 40)/3, 30)];
    _nameT.borderStyle = UITextBorderStyleRoundedRect;
    _nameT.placeholder = @"新建歌单";
    _nameT.clearButtonMode = YES;
    [_addView addSubview:_nameT];
    
    UILabel * label1 = [[UILabel alloc]initWithFrame:CGRectMake(10, 85, 80, 20)];
    label1.text = @"歌单描述";
    label1.textColor = [UIColor whiteColor];
    [_addView addSubview:label1];
    
    _nameT1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 110, (KWIDTH - 40)/3, 30)];
    _nameT1.borderStyle = UITextBorderStyleRoundedRect;
    _nameT1.placeholder = @"简单描述";
    _nameT1.clearButtonMode = YES;
    
    [_addView addSubview:_nameT1];
    
    _iconView = [[UIImageView alloc]initWithFrame:CGRectMake((KWIDTH-40)/1.5, 10,(KWIDTH-40)/4 , (KWIDTH-40)/3)];
    _iconView.userInteractionEnabled = YES;
    _iconView.backgroundColor = [UIColor whiteColor];
    [_addView addSubview:_iconView];
    
    UIButton * addButton = [UIButton buttonWithType:UIButtonTypeSystem];
    addButton.frame = _iconView.bounds;
    addButton.backgroundColor = [UIColor clearColor];
    [addButton addTarget:self action:@selector(addIconView) forControlEvents:UIControlEventTouchUpInside];
    [_iconView addSubview:addButton];
    
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake((KWIDTH-40)/1.5, 30+(KWIDTH-40)/3 , 40, 20);
    [button setTitle:@"取消" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(quxiao) forControlEvents:UIControlEventTouchUpInside];
    
    [_addView addSubview:button];
    
    
    UIButton * button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    button1.frame = CGRectMake((KWIDTH-40)/1.5 + 50, 30+(KWIDTH-40)/3 , 40, 20);
    [button1 addTarget:self action:@selector(ok) forControlEvents:UIControlEventTouchUpInside];
    [button1 setTitle:@"确定" forState:UIControlStateNormal];
    [button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_addView addSubview:button1];
}


// 键盘出现
- (void)keyBoard:(NSNotification *)notication
{
    // 拿到键盘弹出后的一个整体的信息
    NSDictionary * info = notication.userInfo;
    
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    // 拿到键盘的size
    CGSize size = [value CGRectValue].size;
    
    _addView.frame = CGRectMake(20, KHEIGHT/2 - size.height / 2, KWIDTH-40, KWIDTH/2);
}

// 添加键盘回收的通知
- (void)Back:(NSNotification *)notifica
{
  _addView.frame = CGRectMake(20, KHEIGHT/2, KWIDTH-40, KWIDTH/2);
    
}

// 取消
- (void)quxiao
{
    self.nameT.text = nil;
    self.nameT1.text = nil;
    self.iconView.image = nil;
    
    [UIView transitionWithView:_addView duration:1 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        _addView.frame =  CGRectMake((KWIDTH-10)/2, KHEIGHT - 10, 10 , 10);
    } completion:nil];
}

// 确定
- (void)ok
{
    
    
    

    [_db open];
    // 不能重名的表
    
    FMResultSet * rs = [_db executeQuery:@"SELECT * FROM musicList"];
    _nameArray = [NSMutableArray array];
    
    while ([rs next]) {
        musicListModel * model = [[musicListModel alloc]init];
        model.listName = [rs stringForColumn:@"listName"];
        
        [_nameArray addObject:model.listName];
    }
    [rs close];
    
    // 判断表是否存在
    if (_nameT.text.length == 0) {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"表名不能为空" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:cancel];
        cancel.enabled = YES;
        [self presentViewController:alert animated:YES completion:^{
        }];

    }

    else
    {
    
    
     if ([_nameArray containsObject:_nameT.text] ) {
      
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"表名已经存在,请您换一个吧~" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:cancel];
        cancel.enabled = YES;
        [self presentViewController:alert animated:YES completion:^{
            
            _nameT.text = nil;
            _nameT1.text = nil;
            _iconView.image = nil;
   
        }];
    }
    else
    {
        if (self.iconView.image == nil) {
            
            self.iconView.image = [UIImage imageNamed:@"m5"];
            
        }
        
        if (self.nameT1.text.length == 0) {
            
            self.nameT1.text = @"主人太懒没有任何描述";
        }
        
        
        musicListModel * model = [[musicListModel alloc]init];
        
        model.iconViewData = UIImagePNGRepresentation(_iconView.image);
        
        model.listName = _nameT.text;
        
        model.introduce = _nameT1.text;
        

        
        
        
        
    [UIView transitionWithView:_addView duration:1 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        _addView.frame =  CGRectMake((KWIDTH-10)/2, KHEIGHT - 10, 0 , 0);
    } completion:nil];
    

    
    MusicChooseViewController * choose = [[MusicChooseViewController alloc]init];
    
    choose.tableName = _nameT.text;
    
    choose.tableNameModel = model;
    
    [self.navigationController pushViewController:choose animated:YES];
    
    }
    
    }
}

- (BOOL) isTableOK:(NSString *)tableName
{
    
    
    
    
    
    FMResultSet *rs = [self.db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='musicList.db' and listName = ?", tableName];
    while ([rs next])
    {
        NSInteger count = [rs intForColumn:@"count"];
        
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    
    return NO;
}


- (void)addIconView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction * a = [UIAlertAction  actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 判断有没有相机
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                
                UIImagePickerController  * picker = [[UIImagePickerController alloc]init];
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                
                // 是否可编辑 默认是no
                picker.allowsEditing = YES;
                [self presentViewController:picker animated:YES completion:nil];
                picker.delegate = self;
            }
            
            else{
                NSLog(@"没有相机");
            }
            
            
            
        }];
        UIAlertAction * b = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                // 类型：类型决定了 展示出来的是什么（相机还是相册） 相册又分两种形式展示
                UIImagePickerController  * picker = [[UIImagePickerController alloc]init];
                
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                
                // 是否可编辑 默认是no
                picker.allowsEditing = YES;
                // 是一个代理方法 picker 需要设置代理  有两个代理协议 最好点进去看
                picker.delegate = self;
                
                
                [self presentViewController:picker animated:YES completion:nil];
            }
            else
            {
                NSLog(@"没有相册");
            }
        }];
        [alert addAction:cancel];
        [alert addAction:a];
        [alert addAction:b];
        
        
        cancel.enabled = YES;
        [self presentViewController:alert animated:YES completion:nil];
        
    });

}


#pragma mark --- 执行拍摄完成之后 或者选择完照片之后 自动调用的代理方法 ---
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
   
    
    self.iconView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    // 返回到自己的界面
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
   
    _addView.frame = CGRectMake(20, KHEIGHT/2, KWIDTH-40, KWIDTH/2);
}


// 键盘回收
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_nameT resignFirstResponder];
    [_nameT1 resignFirstResponder];
}




#pragma mark --- 返回每个分区的行数 ---
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
     return _modelArray.count +1 + _musicListArray.count ;
}

//// 长按
- (void)longPress:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan ) {
        
        if (longPress.minimumPressDuration == 1)
        {
            
            if (_musicListArray.count != 0) {
                
            
            [_editButton setTitle:@"完成" forState:UIControlStateNormal];
            self.editState = DeleteState;

            
            for (musicrunCell * cell in _conllectionView.visibleCells) {
                
                if (cell.tag < _modelArray.count + _musicListArray.count) {
                    CALayer*viewLayer=[cell layer];
                    CABasicAnimation*animation=[CABasicAnimation
                                                
                                                animationWithKeyPath:@"transform"];
                    animation.duration=0.2;
                    animation.repeatCount = 100000;
                    animation.autoreverses=YES;
                    animation.fromValue=[NSValue valueWithCATransform3D:CATransform3DRotate
                                         
                                         (viewLayer.transform, -0.03, 0.0, 0.0, 0.03)];
                    animation.toValue=[NSValue valueWithCATransform3D:CATransform3DRotate
                                       
                                       (viewLayer.transform, 0.03, 0.0, 0.0, 0.03)];
                    [viewLayer addAnimation:animation forKey:@"wiggle"];
                }
                
                if (cell.tag >=7 && cell.tag < _modelArray.count + _musicListArray.count) {
                        cell.deleteButton.hidden = NO;
                   
                }
            }
                
            }
        }
        
        
    }
}
#pragma mark --- 返回cell ---
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    musicrunCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (_editState == DeleteState) {
        
    
    if (indexPath.row < _modelArray.count + _musicListArray.count) {
        CALayer*viewLayer=[cell layer];
        CABasicAnimation*animation=[CABasicAnimation
                                    
                                    animationWithKeyPath:@"transform"];
        animation.duration=0.2;
        animation.repeatCount = 100000;
        animation.autoreverses=YES;
        animation.fromValue=[NSValue valueWithCATransform3D:CATransform3DRotate
                             
                             (viewLayer.transform, -0.03, 0.0, 0.0, 0.03)];
        animation.toValue=[NSValue valueWithCATransform3D:CATransform3DRotate
                           
                           (viewLayer.transform, 0.03, 0.0, 0.0, 0.03)];
        [viewLayer addAnimation:animation forKey:@"wiggle"];
    }
    }
    // cell 的手势
    _longPressGr = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
    _longPressGr.minimumPressDuration = 1;

    // 添加手势
    [cell.touchView addGestureRecognizer:_longPressGr];

    
    cell.tag = indexPath.row;
    
    cell.backgroundColor = [UIColor clearColor];
    NSInteger a = _modelArray.count + _musicListArray.count;
    
    if (indexPath.row < 7) {
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:_modelArray[indexPath.row]]];
        cell.titlelabel.text = _titleArray[indexPath.row];
        cell.titlelabel.textColor = [UIColor blackColor];
        
         cell.deleteButton.hidden = YES;
    }
    
    else if (indexPath.row < a && indexPath.row >= 7)
    {
        musicListModel * model = _musicListArray[indexPath.row - _modelArray.count];
        
        if (self.editState == DeleteState) {
            cell.deleteButton.hidden = NO;
        }
        else
        {
            cell.deleteButton.hidden = YES;
        }
        
        
        cell.picImageView.image = [UIImage imageWithData:model.iconViewData];
        cell.titlelabel.textColor = [UIColor blackColor];
        cell.titlelabel.text = model.listName;
    
        [cell.deleteButton addTarget:self action:@selector(deleteCell:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    else if(indexPath.row == a)
    {
        cell.deleteButton.hidden = YES;

        cell.titlelabel.text = @"创建歌单";
        cell.titlelabel.textColor = [UIColor blackColor];
        cell.picImageView.image = [UIImage imageNamed:@"6-2"];
        cell.picImageView.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
    }

    
    
    cell.backgroundColor = [UIColor whiteColor];
//    cell.layer.borderColor = [UIColor lightGrayColor].CGColor;
//    cell.layer.borderWidth = 0.5;
    
    return cell;
}

- (void)deleteCell:(UIButton *)button
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"确定删除该歌单？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
 
            
            
            musicrunCell * cell =(musicrunCell *) button.superview.superview;
            NSIndexPath * indexPath = [_conllectionView indexPathForCell:cell];
            [self.musicListArray removeObjectAtIndex:indexPath.row - 7];
            
            
            [_db open];
            
            [_db executeUpdate:@"DELETE FROM musicList Where listName = ?",cell.titlelabel.text];
            
            
            [self.conllectionView reloadData];
            
            // 删除表对应数据库
            NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"chooseMusic.db"];
            
            FMDatabase * db = [FMDatabase databaseWithPath:path];
            
            [db open];
            
            
            [db executeUpdate:@"DELETE FROM chooseMusic Where tableName = ?",cell.titlelabel.text];
            
            
  
            
            
        }];
        UIAlertAction * cancel1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alert addAction:cancel];
        [alert addAction:cancel1];
        cancel.enabled = YES;
        cancel1.enabled = YES;
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
    });

    
    
    
    
    
    
    
    
}


#pragma mark - ModelViewController delegate

- (void)modalViewControllerDidClickedDismissButton:(MusicDetailViewController *)viewController{
    
    self.awesometransition.finalFrame = [viewController.iconView convertRect:viewController.iconView.bounds toView:viewController.view];
    
    viewController.iconView.hidden = YES;
    
    [self dismissViewControllerAnimated:YES completion:^{
        self.transitionCell.hidden = NO;
    }];
}

#pragma mark - transition

- (id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    self.awesometransition.present = YES;
    
    return self.awesometransition;
}


- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    self.awesometransition.present = NO;
    
    return self.awesometransition;
}


// 点击cell 的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_editState == NormalState) {
        
    
    
    NSInteger a = _modelArray.count + _musicListArray.count;

    if (indexPath.row < 7) {
        
        NSString * url = _musicUrlArray[indexPath.row];
        
        MusicDetailViewController * musicDetail = [[MusicDetailViewController alloc]initWithNibName:@"musicDetail" bundle:[NSBundle mainBundle]];
        
        // ------------------------- 动画
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        
       // UIImageView * iconImageView = cell.subviews[0];
        
        musicDetail.transitioningDelegate = self;
        
        musicDetail.delegate              = self;
        
        CGRect startFrame = [cell convertRect:cell.bounds toView:self.view];
        
        CGRect finalFrame = CGRectMake(10, 60, 100, 100);
        
        [self.awesometransition registerStartFrame:startFrame
                                        finalFrame:finalFrame transitionView:cell];
        
        cell.hidden = YES;
        
        self.transitionCell = cell;
        
        // 传值
        musicDetail.urlString = url;
        
        musicDetail.typeString = _titleArray[indexPath.row];
        // 判断点击的
        musicDetail.index = indexPath.row;
        
        __weak MusicDetailViewController * weakVC = musicDetail;
        
        [self presentViewController:musicDetail animated:YES completion:^{
            weakVC.iconView.hidden = NO;
        }];
        
// -------------------------
        
        
    }
   if (indexPath.row<a && indexPath.row >=7)
    {
        MusicDetailViewController * musicDetail = [[MusicDetailViewController alloc]initWithNibName:@"musicDetail" bundle:[NSBundle mainBundle]];
        
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        
        musicDetail.transitioningDelegate = self;
        
        musicDetail.delegate              = self;
        
        CGRect startFrame = [cell convertRect:cell.bounds toView:self.view];
        
        CGRect finalFrame = CGRectMake(10, 60, 100, 100);
        
        [self.awesometransition registerStartFrame:startFrame
                                        finalFrame:finalFrame transitionView:cell];
        
        cell.hidden = YES;
        
        self.transitionCell = cell;

        // 判断点击的
        musicDetail.index = indexPath.row;
        
        musicDetail.musicListArray = _musicListArray;
        
        // 传过去歌单的名字 来找数据库对应的表
        musicrunCell * cell1 = (musicrunCell *)[_conllectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
        musicDetail.tableName  = cell1.titlelabel.text;
        
        
        __weak MusicDetailViewController * weakVC = musicDetail;
        
        [self presentViewController:musicDetail animated:YES completion:^{
            weakVC.iconView.hidden = NO;
        }];

       
        
    }
    
    if (indexPath.row == a) {
        //[self getView];
        
        _nameT.text = nil;
        _nameT1.text = nil;
        _iconView.image = nil;
        
        [UIView transitionWithView:_addView duration:1 options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
        _addView.frame = CGRectMake(20, KHEIGHT/2, KWIDTH-40, KWIDTH/2);
        } completion:nil];
    }
}
    
    
}



#pragma mark --- 返回每个item宽和高 ---
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = (KWIDTH - 40)/3;
    CGFloat height = (KWIDTH - 40)/3 + 35;
    return CGSizeMake(width, height);
}


#pragma mark --- 控制集合视图的行边距 ---
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}


#pragma mark --- 控制集合视图的列边距 ---
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(10, 5, 10, 5);
}





- (void)musiclist
{
    self.musiclistButton.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
    self.mymusicButton.backgroundColor = [UIColor lightGrayColor];
    [UIView animateWithDuration:0.5 animations:^{
        [self.scrolllView setContentOffset:CGPointMake(0, 0)];
        
    }];
}


- (void)mymusic
{
    self.mymusicButton.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
    self.musiclistButton.backgroundColor = [UIColor lightGrayColor];
    [UIView animateWithDuration:0.5 animations:^{
        [self.scrolllView setContentOffset:CGPointMake(KWIDTH, 0)];
    }];
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _scrolllView) {
        if (scrollView.contentOffset.x / KWIDTH == 0) {
            self.musiclistButton.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
            self.mymusicButton.backgroundColor = [UIColor lightGrayColor];
             _editButton.hidden  = NO;
            
            
            self.editState = NormalState;
           //  [self.editButton setTitle:@"编辑" forState:UIControlStateNormal];
           
            for (musicrunCell * cell in _conllectionView.visibleCells) {
                
                cell.deleteButton.hidden = YES;
                
                [cell.layer removeAllAnimations];
                
            }
        }
        else
        {
            [self.editButton setTitle:@"编辑" forState:UIControlStateNormal];

              _editButton.hidden  = YES;
            self.mymusicButton.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
            self.musiclistButton.backgroundColor = [UIColor lightGrayColor];
        }
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        cell.textLabel.text = @"历史";
    }
    else
    {
        cell.textLabel.text = @"收藏";
    }
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        two * t = [[two alloc]init];
        
        [self.navigationController pushViewController:t animated:YES];
        
        t.identifierOne = @"noChoose";
    }
    
    else
    {
    one * o = [[one alloc]init];
        
    [self.navigationController pushViewController:o animated:YES];
        
    o.identifierOne = @"noChoose";
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
